package datastructure.ch05_queues.ch06_circle_queue;

import datastructure.ch05_queues.ch02_interface_abstarct.Queue;

/**
 * 数组实现单向循环队列
 *
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
@SuppressWarnings("unchecked")
public class SingleCircleQueue<E> implements Queue<E> {
    public static void main(String[] args) {
        SingleCircleQueue<Integer> data = new SingleCircleQueue<>();
        data.enqueue(1);
        data.enqueue(2);
        data.enqueue(3);

        System.out.println(data);
        data.dequeue();

        data.enqueue(100);
        System.out.println(data);
        System.out.println(data.front);
        System.out.println(data.size);
    }

    E[] elementData;

    int size;

    int front;

    public SingleCircleQueue() {
        elementData = (E[]) new Object[10];
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void clear() {
        for (int i = 0; i < size; i++) {
            elementData[i] = null;
        }
        size = 0;
        front = 0;
    }

    @Override
    public void enqueue(E e) {
        // 此处的size相当于可以看出索引index
        elementData[(front + size) % elementData.length] = e;
        size++;
    }

    @Override
    public E dequeue() {
        E e = elementData[front];
        elementData[front] = null;
        front = (front + 1) % elementData.length;
        size--;
        return e;
    }

    @Override
    public E getFront() {
        return elementData[0];
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < elementData.length; i++) {
            result.append(elementData[i]);
            if (i < elementData.length - 1) result.append(",");
        }
        return result.toString();
    }
}
